import { Notification } from 'atelement'
import $http from '../../utils/http.js'
import $download from '../../utils/download.js'
import * as esQuery from './utils/esSearch'
import types from './types'

const actions = {
  // 获取省市区（县）级联列表
  [types.GET_LOCATION] ({ commit }, value) {
    $http.post('/api/search/area/list', value).then(({ status, data } = {}) => {
      if (status === 'success') {
        commit(types.SET_LOCATION, data)
      } else if (status === 'fail') {
        Notification.error({
          title: '获取地理位置列表失败'
        })
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
  },
  // 筛选条件 所属机构/系统名称/日志类型
  [types.GET_FILTER_GROUP_OTHER] ({ state, commit }, find) {
    $http.post('/api/search/log/filter/' + find.type, find.condition).then(({ data, status, msg } = {}) => {
      if (status === 'success') {
        // 用于"更多"穿梭框左侧数据
        commit(types.SET_TRANSFER_LEFT, data)
      } else if (status === 'fail') {
        Notification.error({
          title: msg
        })
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
  },
  // 日志类型 中英对照
  [types.GET_STYPE_DICT] ({ state, commit }) {
    $http.post('/api/search/log/filter/stypedict', { type: state.logType }).then(({ data, status, msg } = {}) => {
      if (status === 'success') {
        // 用于"更多"穿梭框左侧数据
        commit(types.SET_STYPE_DICT, data)
      } else if (status === 'fail') {
        Notification.error({
          title: msg
        })
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
  },
  // 根据大的日志类别 获取筛选条件列表
  [types.GET_FILTER_GROUP] ({ state, commit, dispatch }) {
    commit(types.SET_LODING, 'isFilterGroupLoading')
    let p = []
    // 获取系统名、所属机构
    let item = ['sysname', 'affiliation']
    for (let i = 0; i < 2; i++) {
      p[i] = $http.post('/api/search/log/filter/' + item[i]).then(({ data, status, msg } = {}) => {
        if (status === 'success') {
          // 获取筛选条件列表的调用
          commit(types.SET_FILTER_DATA_ITEM, [data, item[i]])
        } else if (status === 'fail') {
          Notification.error({
            title: msg
          })
        } else if (status === 'notallow') {
          Notification.error({
            title: '不具备操作权限'
          })
        }
      })
    }
    let type = { type: state.logType }
    // 获取日志类型
    p[2] = $http.post('/api/search/log/filter/stype', type).then(({ data, status, msg } = {}) => {
      if (status === 'success') {
        // 获取筛选条件列表的调用
        commit(types.SET_FILTER_DATA_ITEM, [data, 'stype'])
      } else if (status === 'fail') {
        Notification.error({
          title: msg
        })
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
    // 获取所属区域、严重级别
    p[3] = $http.post('/api/search/log/filter', type).then(({ status, data } = {}) => {
      if (status === 'success') {
        for (let obj of state.filterCategory) {
          if (data[obj.esKey] !== undefined && data[obj.esKey].length !== 0) {
            commit(types.SET_FILTER_DATA_ITEM, [data[obj.esKey], obj.esKey])
          }
        }
      } else if (status === 'fail') {
        Notification.error({
          title: '获取筛选条件失败'
        })
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
    Promise.all(p).then(results => {
      // 对象的深度拷贝
      let obj = JSON.parse(JSON.stringify(state.filterData))
      commit(types.SET_FILTER_GROUP_COPY, obj)
      commit(types.SET_LODING, 'isFilterGroupLoading')
    })
  },
  // 点击筛选项，获取筛选结果
  [types.GET_LABEL_GROUP] ({ state, commit }, type) {
    if (type !== 'filter') {
      commit(types.CLEAR_FILTER)
    }
    let sendData = JSON.parse(esQuery.getSendData(esQuery.getEsSearch(), state.timeRange))
    commit(types.SET_LODING, 'isTableLoading')
    $http.post('/api/search', sendData).then(({ status, msg, data, searchLine } = {}) => {
      if (status === 'success') {
        commit(types.SET_LABELGROUP, data)
        commit(types.SET_SEARCH_LINE, searchLine)
        commit(types.SET_LODING, 'isTableLoading')
      } else if (status === 'fail') {
        Notification.error({
          message: msg
        })
        commit(types.SET_LODING, 'isTableLoading')
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
  },
  // 主table排序
  [types.GET_HANDLE_SORT] ({ dispatch }, { prop, order }) {
    // order：descending ascending 需处理为 desc 和 asc
    // table无筛选时会传递 null
    order = order === null ? 'descending' : order
    prop = prop === null ? '_source.ts' : prop
    esQuery.setSort(prop.slice(8), order.slice(0, -6))
    dispatch(types.GET_SEARCH, 'filter')
  },
  // 搜索
  // 获取历史搜索
  [types.GET_HISTROY] ({ commit }) {
    $http.get('/api/search/history').then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.SET_HISTORY, data)
      } else if (status === 'fail') {
        Notification.error({
          title: '历史搜索数据获取失败'
        })
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
  },
  // 保存搜索历史
  [types.PUT_SEARCH_HISTORY] (commit, data) {
    $http.post('/api/search/history', { value: data })
  },
  // 获取搜索结果
  [types.GET_SEARCH] ({ state, commit }, type) {
    // if (type !== 'filter' && type !== 'sizeChange') {
    //   commit(types.CLEAR_FILTER)
    // }
    let sendData = JSON.parse(esQuery.getSendData(esQuery.getEsSearch(), state.timeRange))
    commit(types.SET_LODING, 'isTableLoading')
    $http.post('/api/search', sendData).then(({ status, msg, data, searchLine } = {}) => {
      if (status === 'success') {
        commit(types.SET_SEARCH, data)
        commit(types.SET_SEARCH_LINE, searchLine)
        commit(types.SET_LODING, 'isTableLoading')
      } else if (status === 'fail') {
        Notification.error({
          title: '数据获取失败',
          message: msg
        })
        commit(types.SET_LODING, 'isTableLoading')
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
  },
  // 导出
  // 导出全部(json文件)
  [types.DOWNLOAD_JSONFILE_All] ({ state }) {
    let sendData = state.searchLine
    $download.post('/api/search/export/events/json', { searchLine: JSON.stringify(sendData) })
  },
  // 导出选中(json文件)
  [types.DOWNLOAD_JSONFILE] (commit, data) {
    let sendData = []
    for (let el of data) {
      sendData.push(el._source)
    }
    $download.post('/api/search/export/single/json', { json: JSON.stringify(sendData) })
  },
  // 导出选中(excel)
  [types.DOWNLOAD_EXCELFILE] ({ commit, state }, data) {
    let sendData = []
    for (let el of data) {
      sendData.push(el._source)
    }
    $download.post('/api/search/export/single/excel', { event_type: state.logType, json: JSON.stringify(sendData) })
  },
  // 导出全部(excel)
  [types.DOWNLOAD_EXCELFILE_ALL] ({ state }) {
    let sendData = {
      searchLine: JSON.stringify(state.searchLine),
      event_type: state.logType
    }
    $download.post('/api/search/export/events/excel', sendData)
  },
  // 聚合区
  // 聚合 json下载
  [types.POST_ECHART_JSON] ({ state }, index) {
    let sendData = {
      name: state.groupCategory[index].key.split('.').pop(),
      data: JSON.stringify(state.searchLine)
    }
    $download.post('/api/search/export/aggs/json', sendData)
  },
  // 聚合 获取echarts数据
  [types.GET_ECHARTS] ({ state, commit }, el) {
    let aggs = state.groupCategory[el.key].groupSearch(state.groupCategory[el.key].key)
    let groupKey = state.groupCategory[el.key].groupKey
    esQuery.setEsAggs(aggs)
    let sendData = JSON.parse(esQuery.getSendData(esQuery.getEsQueryBody(), state.timeRange))
    commit(types.SET_LODING, 'isGroupDetailLoading')
    $http.post('/api/search', sendData).then(({ status, msg, data, searchLine } = {}) => {
      if (status === 'success') {
        let result = data.aggregations
        for (let itemKey of groupKey.split('.')) {
          result = result[itemKey]
        }
        result = result.buckets
        // 去空值
        for (let index in result) {
          if (result[index].key === '') {
            result.splice(index, 1)
          }
        }
        // 聚合 日志类型 英文转中文
        let type = state.groupCategory[el.key].key
        let finalResult = []
        if (type === 'stype') {
          for (let item of result) {
            finalResult.push({
              key: state.stypeDict[item.key] === undefined ? item.key : state.stypeDict[item.key],
              doc_count: item.doc_count
            })
          }
        } else {
          finalResult = result
        }
        commit(types.SET_GROUP_PIC, finalResult)
        // // searchLine 供“聚合详情下载任务使用”
        commit(types.SET_SEARCH_LINE, searchLine)
        commit(types.SET_LODING, 'isGroupDetailLoading')
      } else if (status === 'fail') {
        Notification.error({
          title: '绘图失败'
        })
        commit(types.SET_LODING, 'isGroupDetailLoading')
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
  },
  // 详情页
  // 详情页获取数据
  [types.GET_DETAIL_DATA] ({ commit }, value) {
    $http.post('/api/search/id', { id: value }).then(({ status, data, msg } = {}) => {
      if (status === 'success') {
      } else if (status === 'fail') {
        Notification.error({
          title: '详情信息获取失败'
        })
      } else if (status === 'notallow') {
        Notification.error({
          title: '不具备操作权限'
        })
      }
    })
  },
  // 详情页 下载JSON文件
  [types.DOWNLOAD_SINGLE_JSONFILE] (commit, data) {
    $download.post('/api/search/export/single/json', { json: JSON.stringify(data) })
  }
}

export default actions
